package com.anne.fish.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.anne.fish.service.AreaManager;
import com.anne.fish.model.Area;
import com.anne.fish.webapp.action.BaseAction;

import java.util.List;

public class AreaAction extends BaseAction implements Preparable {
    private AreaManager areaManager;
    private List areas;
    private Area area;
    private Long id;
    private String query;

    public void setAreaManager(AreaManager areaManager) {
        this.areaManager = areaManager;
    }

    public List getAreas() {
        return areas;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String areaId = getRequest().getParameter("area.id");
            if (areaId != null && !areaId.equals("")) {
                area = areaManager.get(new Long(areaId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        areas = areaManager.search(query, Area.class);
        return SUCCESS;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Area getArea() {
        return area;
    }

    public void setArea(Area area) {
        this.area = area;
    }

    public String delete() {
        areaManager.remove(area.getId());
        saveMessage(getText("area.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            area = areaManager.get(id);
        } else {
            area = new Area();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (area.getId() == null);

        areaManager.save(area);

        String key = (isNew) ? "area.added" : "area.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}